import { Injectable } from '@nestjs/common';
import { Affiliate } from "../model/Affiliate";
import { BaseService } from "./BaseService";
import * as AffiliateReq from '../model/req/AffiliateReq';
import { Repository, SelectQueryBuilder, UpdateResult, ObjectLiteral } from "typeorm";
@Injectable()
export default class MemberService<T extends ObjectLiteral> extends BaseService<T> {
    constructor() {
        super(Affiliate);
    }

    /**
     * @description: 根据会员id查询会员信息
     * @param {string} affiliate_id
     * @return {*}
     */
    async getAffiliate(affiliate_id: string): Promise<T | string> {
        const data = await this.repository.createQueryBuilder().where({ affiliate_id }).getOne();
        return data ? data : "affiliate_id错误";
    }

    /**
     * @description: 根据会员id关闭会员
     * @param {AffiliateReq} body
     * @return {*}
     */
    async setAffiliateState(body: AffiliateReq.setAffiliateReq): Promise<T | string> {
        const existing: any = await this.getAffiliate(body.affiliate_id);
        if (typeof existing == "string") {
            return existing
        }
        existing.affiliate_state = 0;
        existing.affiliate_update_time = new Date();
        return await this.repository.save(existing);
    }

    /**
     * @description: 根据会员id删除
     * @param {AffiliateReq} body
     * @return {*}
     */
    async delAffiliate(body: AffiliateReq.setAffiliateReq): Promise<T | string> {
        const existing = await this.getAffiliate(body.affiliate_id);
        if (typeof existing == "string") {
            return existing
        }
        const result = await this.repository.delete(body.affiliate_id);
        if (result.affected === 1) {
            return {} as T;
        } else {
            return "删除失败";
        }
    }


    async addAffiliate(body: any): Promise<T | string> {
        return await this.repository.save(body);
    }


}